// import { createStore } from "redux";
import { createStore, applyMiddeware } from "../my-redux";

import combineReducer from "./reducers";

// 实现中间件：日志打印
function logger({ getState, dispatch }) {
  return function (oldDispatch) {
    return function (action) {
      console.log("旧状态：", getState());
      oldDispatch(action); // 执行 store 仓库中的 dispatch 方法
      console.log("新状态：", getState());
      return action;
    };
  };
}

// 实现中间件：异步请求
function thunk({ getState, dispatch }) {
  return function (next) {
    return function (action) {
      if (typeof action === "function") {
        return action(getState, dispatch);
      }

      return next(action);
    };
  };
}

// 实现中间件：promise
function promise({ getState, dispatch }) {
  return function (next) {
    return function (action) {
      if (action.then && typeof action.then === "function") {
        return action.then(dispatch);
      }

      return next(action);
    };
  };
}

// const store = applyMiddeware(logger)(createStore)(combineReducer);
// const store = applyMiddeware(thunk)(createStore)(combineReducer);
// const store = applyMiddeware(promise)(createStore)(combineReducer);

// logger、thunk、promise 组合在一起使用
const chainMiddeware = applyMiddeware(thunk, promise, logger);
const store = chainMiddeware(createStore)(combineReducer);
export default store;
